<template>
  <el-row :gutter="20">
    <!-- 1) 近7天交易金额折线图 -->
    <el-col :span="12">
      <div ref="lineChartRef" style="width: 100%; height: 400px;"></div>
    </el-col>

    <!-- 2) 交易类型（欺诈的）的扇形图 -->
    <el-col :span="12">
      <div ref="fraudTypePieRef" style="width: 100%; height: 400px;"></div>
    </el-col>
  </el-row>

  <el-row :gutter="20" style="margin-top: 20px">
    <!-- 3) 地理位置（欺诈的）的扇形图 -->
    <el-col :span="12">
      <div ref="fraudLocationPieRef" style="width: 100%; height: 400px;"></div>
    </el-col>

    <!-- 4) 商户类型（欺诈的）柱形图 -->
    <el-col :span="12">
      <div ref="fraudMerchantBarRef" style="width: 100%; height: 400px;"></div>
    </el-col>
  </el-row>

  <el-row :gutter="20" style="margin-top: 20px">
    <!-- 5) 是否IP地址标识的柱形图 -->
    <el-col :span="12">
      <div ref="ipAddressFlagBarRef" style="width: 100%; height: 400px;"></div>
    </el-col>

    <!-- 6) 近7日诈骗和未诈骗数量的折线图 -->
    <el-col :span="12">
      <div ref="fraudVsNotFraud7dLineRef" style="width: 100%; height: 400px;"></div>
    </el-col>
  </el-row>

  <el-row :gutter="20" style="margin-top: 20px">
    <!-- 7) 交易距离的扇形图 -->
    <el-col :span="12">
      <div ref="distancePieRef" style="width: 100%; height: 400px;"></div>
    </el-col>

    <!-- 8) 各个有数值的字段总和（使用表格简单展示） -->
    <el-col :span="12">
      <el-table
          :data="[numericSums]"
          style="width: 100%;"
          v-if="numericSums"
      >
        <el-table-column
            label="总交易金额"
            prop="total_transaction_amount"
        />
        <el-table-column
            label="总账户余额"
            prop="total_account_balance"
        />
        <el-table-column
            label="历史欺诈总次数"
            prop="total_previous_fraudulent_activity"
        />
        <el-table-column
            label="当日交易总次数"
            prop="total_daily_transaction_count"
        />
        <el-table-column
            label="7天平均交易额之和"
            prop="total_avg_transaction_amount_7d"
        />
        <el-table-column
            label="7天失败交易总次数"
            prop="total_failed_transaction_count_7d"
        />
        <el-table-column
            label="卡龄总和"
            prop="total_card_age"
        />
        <el-table-column
            label="交易距离总和"
            prop="total_transaction_distance"
        />
        <el-table-column
            label="风险分数总和"
            prop="total_risk_score"
        />
      </el-table>
    </el-col>
  </el-row>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import * as echarts from 'echarts'
import { getChartsData } from '@/api/visualization' // 按实际路径修改

// 1) DOM 元素的引用
const lineChartRef = ref(null)
const fraudTypePieRef = ref(null)
const fraudLocationPieRef = ref(null)
const fraudMerchantBarRef = ref(null)
const ipAddressFlagBarRef = ref(null)
const fraudVsNotFraud7dLineRef = ref(null)
const distancePieRef = ref(null)

// 2) 响应式数据
const chartsData = reactive({
  last_7d_amount_data: [],
  fraud_by_type_data: [],
  fraud_by_location_data: [],
  fraud_by_merchant_data: [],
  ip_address_flag_data: [],
  fraud_vs_notfraud_7d_data: [],
  distance_pie_data: []
})

// 3) 数值汇总对象
const numericSums = reactive({})

// 4) 图表实例（初始化后赋值）
let lineChartInstance = null
let fraudTypePieInstance = null
let fraudLocationPieInstance = null
let fraudMerchantBarInstance = null
let ipAddressFlagBarInstance = null
let fraudVsNotFraud7dLineInstance = null
let distancePieInstance = null

// 生命周期：组件挂载完毕后请求数据并初始化图表
onMounted(async () => {
  await fetchChartsData()
  initCharts()
})

// 请求后端数据
async function fetchChartsData() {
  try {
    const res = await getChartsData() // 后端 /get_charts_data 接口

      chartsData.last_7d_amount_data = res.last_7d_amount_data
      chartsData.fraud_by_type_data = res.fraud_by_type_data
      chartsData.fraud_by_location_data = res.fraud_by_location_data
      chartsData.fraud_by_merchant_data = res.fraud_by_merchant_data
      chartsData.ip_address_flag_data = res.ip_address_flag_data
      chartsData.fraud_vs_notfraud_7d_data = res.fraud_vs_notfraud_7d_data
      chartsData.distance_pie_data = res.distance_pie_data
      Object.assign(numericSums, res.numeric_sums)

  } catch (err) {
    console.error('获取图表数据失败: ', err)
  }
}

// 初始化 ECharts 图表
function initCharts() {
  // (1) 近7天交易金额折线图
  lineChartInstance = echarts.init(lineChartRef.value)
  const lineOption = {
    title: { text: '近7天交易金额' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: chartsData.last_7d_amount_data.map(item => item.date)
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '交易金额',
        type: 'line',
        data: chartsData.last_7d_amount_data.map(item => item.total_amount)
      }
    ]
  }
  lineChartInstance.setOption(lineOption)

  // (2) 交易类型（欺诈的）扇形图
  fraudTypePieInstance = echarts.init(fraudTypePieRef.value)
  const fraudTypePieOption = {
    title: { text: '交易类型(欺诈)', left: 'center' },
    tooltip: { trigger: 'item' },
    series: [
      {
        name: 'Fraud Count',
        type: 'pie',
        radius: '50%',
        data: chartsData.fraud_by_type_data.map(item => ({
          value: item.fraud_count,
          name: item.transaction_type
        }))
      }
    ]
  }
  fraudTypePieInstance.setOption(fraudTypePieOption)

  // (3) 地理位置（欺诈的）扇形图
  fraudLocationPieInstance = echarts.init(fraudLocationPieRef.value)
  const fraudLocationPieOption = {
    title: { text: '地理位置(欺诈)', left: 'center' },
    tooltip: { trigger: 'item' },
    series: [
      {
        name: 'Fraud Count',
        type: 'pie',
        radius: '50%',
        data: chartsData.fraud_by_location_data.map(item => ({
          value: item.fraud_count,
          name: item.location
        }))
      }
    ]
  }
  fraudLocationPieInstance.setOption(fraudLocationPieOption)

  // (4) 商户类型（欺诈的）柱形图
  fraudMerchantBarInstance = echarts.init(fraudMerchantBarRef.value)
  const barOptionMerchant = {
    title: { text: '商户类型(欺诈)' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: chartsData.fraud_by_merchant_data.map(item => item.merchant_category)
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: 'Fraud Count',
        type: 'bar',
        data: chartsData.fraud_by_merchant_data.map(item => item.fraud_count)
      }
    ]
  }
  fraudMerchantBarInstance.setOption(barOptionMerchant)

  // (5) 是否IP地址标识的柱形图
  ipAddressFlagBarInstance = echarts.init(ipAddressFlagBarRef.value)
  const barOptionIp = {
    title: { text: '是否IP可疑(0=No,1=Yes)' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: chartsData.ip_address_flag_data.map(item => item.ip_address_flag)
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: 'Count',
        type: 'bar',
        data: chartsData.ip_address_flag_data.map(item => item.total_count)
      }
    ]
  }
  ipAddressFlagBarInstance.setOption(barOptionIp)

  // (6) 近7日诈骗和未诈骗数量折线图
  fraudVsNotFraud7dLineInstance = echarts.init(fraudVsNotFraud7dLineRef.value)
  const dates = chartsData.fraud_vs_notfraud_7d_data.map(item => item.date)
  const fraudCounts = chartsData.fraud_vs_notfraud_7d_data.map(item => item.fraud_count)
  const notFraudCounts = chartsData.fraud_vs_notfraud_7d_data.map(item => item.not_fraud_count)
  const lineOptionFraudVsNot = {
    title: { text: '近7日 诈骗 vs 未诈骗' },
    tooltip: { trigger: 'axis' },
    legend: { data: ['Fraud', 'Not Fraud'] },
    xAxis: { type: 'category', data: dates },
    yAxis: { type: 'value' },
    series: [
      { name: 'Fraud', type: 'line', data: fraudCounts },
      { name: 'Not Fraud', type: 'line', data: notFraudCounts }
    ]
  }
  fraudVsNotFraud7dLineInstance.setOption(lineOptionFraudVsNot)

  // (7) 交易距离的扇形图
  distancePieInstance = echarts.init(distancePieRef.value)
  const distancePieOption = {
    title: { text: '交易距离分布', left: 'center' },
    tooltip: { trigger: 'item' },
    series: [
      {
        name: 'Count',
        type: 'pie',
        radius: '50%',
        data: chartsData.distance_pie_data.map(item => ({
          value: item.cnt,
          name: item.distance_range
        }))
      }
    ]
  }
  distancePieInstance.setOption(distancePieOption)
}
</script>

<style scoped>
/* 根据需要自定义样式 */
</style>
